<?php

namespace app\index\controller;

use app\common\controller\Index;

class Subject extends Index
{
    protected $noNeedLogin = ['search','subject'];
    // 构造函数继承父类
    public function __construct()
    {
        parent::__construct();

        $this->SubjectModel = model('Subject.Subject');

        $this->ListsModel = model('Subject.Lists');

        $this->OrderModel = model('Subject.Order');

        $this->RecordModel = model('Business.Record');

        $this->CommentModel = model('Subject.Comment');
    }

    public function search(){
        if($this->request->isGet()){
            // 获取搜索跳转的传值
            $search = $this->request->param('indexSearch','','trim');

            // 创建布尔值，默认为假
            $search_bool = false;

            // 创建新数组装判断条件
            $where = [];

            // 如果搜索框为空 
            if(!empty($search)){
                $where['title|content'] = ['like',"%$search%"];
            }

            // 查询搜索的相关课程
            $sublist = $this->SubjectModel->where($where)-> select();

            // 如果查询无相关课程，打印出所有课程
            if(!$sublist){
                $sublist = $this->SubjectModel->field(true)->select();
                $search_bool = true;
                $this->view->assign([
                    'sublist' => $sublist,
                    'search' => $search,
                    'search_bool' => $search_bool,
                ]);
            }

            $this->view->assign([
                'sublist' => $sublist,
                'search' => $search,
                'search_bool' => $search_bool
            ]);

        }
        return $this->view->fetch();
    }
    public function subject($subid = 0){
        $subject = $this->SubjectModel->find($subid);
        $subject = $subject->toArray();

        $like = isset($subject['likes'])?trim($subject['likes']):null;

        if(!$subject){
            $this->error('目前无课程','/index/index/index');
            exit;
        }

        $loginUser = cookie('LoginUser')?cookie('LoginUser'):[];
        
        $user_id = isset($loginUser['id'])?$loginUser['id']:0;

        $user_mobile = isset($loginUser['mobile'])?$loginUser['mobile']:'';

        $where = [
            'id' => $user_id,
            'mobile' => $user_mobile,
        ];

        // 获取当前章节点赞的所有人id
        $like_str = trim($subject['likes']);
        $like_arr = array_filter(explode(',',$like_str));
        $like_num = count($like_arr);

        // 如果为真则点赞过，为假则没点赞
        $likes = in_array($user_id,$like_arr)? true:false;

        $list = $this->ListsModel->where(['subid'=>$subid])->order('createtime ASC')->select();
        if(!$list){
            $this->error('当前课程暂无章节');
            exit;
        }
        $list = collection($list)->toArray();

        // 引入评论
        $where = [
            'subid'=>$subid,
        ];
        $comment_list = $this->CommentModel->with(['lists'])->where($where)->select();
        $comment = collection($comment_list)->toArray();
        $comment_list = [];
        foreach($comment as $key=>$item){
            $item['bus_text'] = '';
            if($item['busid'] == null){
                $item['bus_text'] = '/assets/index/images/pexels-spencer-selover-428364.jpg';
                $comment_list[] = $item;
            }else{
                $business = $this->BusinessModel->where(['id'=>$item['busid']])->find();
                $item['bus_text'] = $business['avatar'];
                $comment_list[] = $item;
            }
        }
        // var_dump(collection($comment_list)->toArray());

        $this->view->assign([
            'subject' => $subject,
            'lists' => $list,
            'likes_booler' => $likes,
            'like_num' => $like_num,
            'comment' => $comment_list,
        ]);

        return $this->view->fetch();
    }

    public function likes()
    {
        if($this->request->isAjax())
        {
            $loginUser = cookie('LoginUser')?cookie('LoginUser'):[];

            $user_id = isset($loginUser['id']) ? $loginUser['id'] : 0;
            $user_mobile = isset($loginUser['mobile']) ? $loginUser['mobile'] : '';

            $where = [
                'id' => $user_id,
                'mobile' => $user_mobile,
            ];

            $sql = $this->BusinessModel->where($where)->find();
            if(!$sql){
                cookie('LoginUser',null);
                $this->error('登录非法，请重新登录');
                exit;
            }

            $subid = $this->request->param('subid');
            $subject = $this->SubjectModel->find($subid);

            if(!$subject){
                $this->error('当前选择课程不存在');
                exit;
            }

            $data = [
                'id' => $subid,
                'likes' => $user_id,
            ];

            if($subject['likes'] == null){
                $sql = $this->SubjectModel->isUpdate(true)->save($data);
                if($sql == false){
                    $this->error("点赞失败");
                    exit;
                }else{
                    $this->success("点赞成功");
                    exit;
                }
            }
            $sublist = explode(',',$subject['likes']);
            $sublist = array_filter($sublist);
            if(in_array($user_id,$sublist)){
                foreach($sublist as $key=>$item){
                    if($user_id == $item){
                        unset($sublist[$key]);
                        break;
                    }
                }
                $msg = '取消点赞';
            }else{
                $sublist[] = $user_id;
                $msg = '点赞';
            }
            $data = [
                'id' => $subid,
                'likes' => implode(',',$sublist),
            ];
            $sql = $this->SubjectModel->isUpdate(true)->save($data);
            if($sql == false){
                $this->error("{$msg}失败");
                exit;
            }else{
                $this->success("{$msg}成功");
                exit;
            }
        }
    }
    public function course(){
        if($this->request->isAjax()){
            $loginUser = cookie('LoginUser')?cookie('LoginUser'):[];
            if(!$loginUser){
                $this->error('','index/index/login');
                exit;
            }
            $subid = $this->request->param('subid');
            $LoginUser = cookie('LoginUser')?cookie('LoginUser'):[];
            $busid = isset($LoginUser['id'])?$LoginUser['id']:0;
            $where = [
                'subid'=>$subid,
                'busid'=>$busid,
            ];
            $sql = $this->OrderModel->where($where)->find();

            $list_url = $this->ListsModel->where(['subid'=>$subid])->order('id asc')->select();
            $list_url = collection($list_url)->toArray();
            $player = isset($list_url[0]['url'])?$list_url[0]['url']:'';
            if(!$sql){
                // 没有购买课程
                $this->error('没有购买课程');
                exit;
            }else{
                $this->success('已购买课程',null,$player);
                exit;
            }
        }
    }
    public function play(){
        if($this->request->isAjax()){
            $subid = $this->request->param('subid',0);
            $busid = $this->loginAuth['id'];

            // 查询课程

            $sql = $this->SubjectModel->find($subid);

            if(!$sql){
                $this->error('暂无当前课程');
                exit;
            }
            
            $subject = $sql;
            // 查询是否购买课程
            $where = [
                'subid'=>$subid,
                'busid'=>$busid,
            ];

            $sql = $this->OrderModel->where($where)->find();

            if($sql){
                $this->success('已购买课程');
                exit;
            }

            $price = isset($subject['price']) ? trim($subject['price']) : 0 ;

            // 获取账户余额
            $sql = $this->BusinessModel->find($busid);

            if(!$sql){
                $this->error('当前无账户',cookie('LoginUser',null));
                exit;
            }

            $user = $sql;
            $money = isset($user['money'])?trim($user['money']):0.00;

            $CensorMoney = bcsub($money,$price);

            if($CensorMoney < 0){
                $this->error('余额不足，请先充值');
                exit;
            }
            
            // 开启事务（带回滚，类似gitee）
            $this->OrderModel->startTrans();
            $this->BusinessModel->startTrans();
            $this->RecordModel->startTrans();

            // 生成订单
            $code = build_code("SU");

            $OrderData = [
                'subid' => $subid,
                'busid' => $busid,
                'total' => $price,
                'code' => $code,
            ];

            $OrderStatus = $this->OrderModel->validate('common/Subject/Order')->save($OrderData);

            if(!$OrderStatus){
                $this->error($this->OrderModel->getError());
                exit;
            }

            $BusData = [
                'id' => $busid,
                'money' => $CensorMoney,
            ];

            if(!$this->loginAuth['deal']){
                $BusData['deal'] = 1;
            }

            $BusStatus = $this->BusinessModel->isUpdate(true)->save($BusData);

            // 数据库事务回滚
            if(!$BusStatus){
                $this->OrderModel->rollback();
                $this->error($this->BusinessModel->getError());
                exit;
            }

            $subtitle = $subject['title'];
            $RecordData = [
                'total' => "-{$price}",
                'content' => "购买了【{$subtitle}】课程",
                'busid' => $busid,
            ];

            $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);

            if(!$RecordStatus){
                $this->BusinessModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->RecordModel->getError());
                exit;
            }

            if($OrderStatus === false||$BusStatus === false||$RecordStatus === false){
                $this->RecordModel->rollback();
                $this->BusinessModel->rollback();
                $this->OrderModel->rollback();
                $this->error('购买失败');
                exit;
            }else{
                // 运行成功，提交事务，执行写入数据库
                $this->OrderModel->commit();
                $this->BusinessModel->commit();
                $this->RecordModel->commit();
                $this->success('购买成功');
                exit;
            }
        }
    }

    public function complete($subid = 0){

    }
}
